﻿
Imports System.Threading

Class Application

    ' Startup、Exit、DispatcherUnhandledException などのアプリケーション レベルのイベントは、
    ' このファイルで処理できます。

    Private Shared MyMutex As Mutex
    Private Shared Window As MainWindow

    Private Sub Application_DispatcherUnhandledException(ByVal sender As Object, ByVal e As System.Windows.Threading.DispatcherUnhandledExceptionEventArgs) Handles Me.DispatcherUnhandledException

        Dim time = Now.ToString("HH:mm")
        Window.AddStatusBarText(String.Format("{0} 内部エラー: {1}", time, e.Exception.Message))
        
    End Sub

    Private Sub Application_Exit(ByVal sender As Object, ByVal e As System.Windows.ExitEventArgs) Handles Me.Exit
        If MyMutex IsNot Nothing Then
            MyMutex.ReleaseMutex()
            MyMutex.Close()
        End If
    End Sub

    <System.STAThreadAttribute(), _
     System.Diagnostics.DebuggerNonUserCodeAttribute()> _
    Public Shared Sub Main()

#If Not Debug Then

        ' 名前を指定してMutexを生成 
        MyMutex = New Mutex(False, My.Resources.ApplicationName)

        ' 二重起動をチェック
        If Not MyMutex.WaitOne(0, False) Then

            MyMutex.Close()
            MyMutex = Nothing

            ' 同名のプロセスが他に存在する場合は、既に起動していると判断
            Dim current = System.Diagnostics.Process.GetCurrentProcess()
            Dim ps = System.Diagnostics.Process.GetProcessesByName(current.ProcessName)
            For Each p In ps
                If current.Id <> p.Id Then
                    ' TODO タスクトレイに格納されている場合
                    NativeMethods.ShowWindow(p.MainWindowHandle, NativeMethods.SW_SHOWNORMAL)
                    NativeMethods.SetForegroundWindow(p.MainWindowHandle)
                    Exit For
                End If
            Next

            Exit Sub
        End If
#End If

        Dim app = New Application
        app.Run()
    End Sub

    Protected Overrides Sub OnStartup(ByVal e As StartupEventArgs)
        MyBase.OnStartup(e)

        Window = New MainWindow
        Dim settings = LoadSettings()
        Window.Start()

        If settings IsNot Nothing AndAlso Not settings.General.IsInTray Then
            Window.Show()
        End If

    End Sub

    ' 起動時タスクトレイ格納対応のため 一度ここで設定取得
    Private Function LoadSettings() As UserSettings
        Dim settings = New UserSettings
        Try
            Dim userDataPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Co9320\NamaAlert\1.0.0.0")
            Dim settingsFile = System.IO.Path.Combine(userDataPath, My.Resources.UserSettingsFile)
            If Not System.IO.File.Exists(settingsFile) Then
                Return Nothing
            End If

            Dim document = XDocument.Load(settingsFile)


            If document.<settings>.Elements.Count > 0 Then
                settings.Deserialize(document.<settings>.Elements.First)

                If document.<settings>.<UI>.<MainWindow>.Count > 0 Then
                    Dim el = document.<settings>.<UI>.<MainWindow>.First

                    If el.<Width>.Value IsNot Nothing Then
                        Window.Width = CInt(el.<Width>.Value)
                    End If
                    If el.<Height>.Value IsNot Nothing Then
                        Window.Height = CInt(el.<Height>.Value)
                    End If

                    If el.<Left>.Value IsNot Nothing Then
                        Window.Left = CInt(el.<Left>.Value)
                    End If
                    If el.<Top>.Value IsNot Nothing Then
                        Window.Top = CInt(el.<Top>.Value)
                    End If
                End If
            End If

            If settings.General.IsInTray Then
                Window.Visibility = Visibility.Collapsed
            End If

        Catch ex As Exception

        End Try
        Return settings

    End Function


End Class
